package com.example.questionnairespringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.questionnairespringboot.beans.HttpResponseEntity;
import com.example.questionnairespringboot.entity.Question;
import com.example.questionnairespringboot.entity.QuestionOption;
import com.example.questionnairespringboot.entity.Questionnaire;
import com.example.questionnairespringboot.service.IQuestionnaireService;

import java.util.ArrayList;
import java.util.List;

import nonapi.io.github.classgraph.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.oas.annotations.EnableOpenApi;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

@EnableOpenApi
@RestController
@RequestMapping("/questionnaire")
public class QuestionnaireController {

    @Autowired
    private IQuestionnaireService questionnaireServiceImpl;

    @RequestMapping(value = "/setQuestionnaireQuestion", method = RequestMethod.POST, headers = "Accept=application/json")
    public HttpResponseEntity setQuestionnaireQuestion(@RequestBody String da) {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        Integer id = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(da, JSONObject.class);
            id=jsonObject.getObject("Id", Integer.class);
            Questionnaire questionnaire;
            if(id==null){
                questionnaire =new Questionnaire();
            }
            else{
                questionnaire = questionnaireServiceImpl.getById(id);
            }
            questionnaire.setInstructions(jsonObject.getObject("Instructions", String.class));
            questionnaire.setName(jsonObject.getObject("Name", String.class));
            ArrayList<Question> questionList = new ArrayList<Question>();

            JSONArray jsonArray = jsonObject.getJSONArray("questionList");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject obj = (JSONObject) jsonArray.get(i);
                JSONArray array = obj.getJSONArray("questionOption");
                ArrayList<QuestionOption> qo = new ArrayList<QuestionOption>();
                for (int j = 0; j < array.size(); j++) {
                    JSONObject qoobj = (JSONObject) array.get(j);
                    qo.add(new QuestionOption(qoobj.getObject("lineTitle", String.class),
                        qoobj.getObject("optionGrade", String.class),
                        qoobj.getObject("optionWord", String.class)));
                }
                questionList.add(new Question(obj.getObject("important", String.class), qo,
                    obj.getObject("questionTitle", String.class),
                    obj.getObject("questionType", String.class)));
            }
            if (questionList != null && questionList.size() != 0) {
                String str = JSON.toJSONString(questionList);
                questionnaire.setQuestions(str);
                questionnaireServiceImpl.saveOrUpdate(questionnaire);
            }
            httpResponseEntity.setData(questionnaire.getId());
            httpResponseEntity.setCode("666"); //成功返回代码666
            httpResponseEntity.setMessage("题目信息已保存！");
        } catch (Exception e) {
//            logger.info("addUserInfo 创建用户的基本信息>>>>>>>>>>>" + e.getLocalizedMessage());
            httpResponseEntity.setCode("20001");
            httpResponseEntity.setMessage("系统异常");
        }
        return httpResponseEntity;
    }
    @GetMapping("/page")
    public IPage<Questionnaire> findPage(@RequestParam Integer pageNum,
                                  @RequestParam Integer pageSize, @RequestParam(defaultValue = "") String Name) {
        IPage<Questionnaire> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Questionnaire> queryWrapper = new QueryWrapper<>();
        if(!"".equals(Name)){
            queryWrapper.like("Name",Name);
        }
        return questionnaireServiceImpl.page(page,queryWrapper);
    }

    @RequestMapping(value = "/queryQuestionnaireById", method = RequestMethod.POST, headers = "Accept=application/json")
//    @PostMapping(value = "queryQuestionnaireById",headers = "Accept=application/json")
    public HttpResponseEntity queryQuestionnaireById(@RequestBody Integer Id) {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
//            System.out.printf(String.valueOf(questionnaireServiceImpl.getById(questionnaire.getId())));
//            System.out.println(questionnaireServiceImpl.getById(questionnaireId));
            httpResponseEntity.setData(
                    questionnaireServiceImpl.getById(Id));
            httpResponseEntity.setCode("666"); //成功返回代码666
//            httpResponseEntity.setMessage("删除成功");

        } catch (Exception e) {
//            logger.info("addUserInfo 创建用户的基本信息>>>>>>>>>>>" + e.getLocalizedMessage());
            httpResponseEntity.setCode("20001");
            httpResponseEntity.setMessage("系统异常");
        }
        return httpResponseEntity;
    }

    @RequestMapping(value = "/queryQuestionnaireQuestion", method = RequestMethod.POST, headers = "Accept=application/json")
//    @PostMapping(value = "queryQuestionnaireQuestion",headers = "Accept=application/json")
    public HttpResponseEntity queryQuestionnaireQuestion(@RequestBody Integer Id) {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
//            httpResponseEntity.setData(
//                    questionnaireServiceImpl.getById(questionnaire.getId()));
                Questionnaire req = new Questionnaire();
                req = questionnaireServiceImpl.getById(Id);
                if (!(req.getQuestions() == null) && !req.getQuestions()
                        .equals("")) {
                    String da = req.getQuestions();

                    JSONArray jsonArray = JSONObject.parseObject(da, JSONArray.class);

                    ArrayList<Question> questionlist = new ArrayList<Question>();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject obj = (JSONObject) jsonArray.get(i);
                        JSONArray array = obj.getJSONArray("questionOption");
                        ArrayList<QuestionOption> qo = new ArrayList<QuestionOption>();
                        for (int j = 0; j < array.size(); j++) {
                            JSONObject qoobj = (JSONObject) array.get(j);
                            qo.add(new QuestionOption(qoobj.getObject("lineTitle", String.class),
                                    qoobj.getObject("optionGrade", String.class),
                                    qoobj.getObject("optionWord", String.class)));
                        }
                        questionlist.add(new Question(obj.getObject("important", String.class), qo,
                                obj.getObject("questionTitle", String.class),
                                obj.getObject("questionType", String.class)));
                    }

                    httpResponseEntity.setData(questionlist);
                    httpResponseEntity.setCode("666");
                } else {
                    httpResponseEntity.setData(null);
                }





            httpResponseEntity.setCode("666"); //成功返回代码666
//            httpResponseEntity.setMessage("删除成功");

        } catch (Exception e) {
//            logger.info("addUserInfo 创建用户的基本信息>>>>>>>>>>>" + e.getLocalizedMessage());
            httpResponseEntity.setCode("20001");
            httpResponseEntity.setMessage("系统异常");
        }
        return httpResponseEntity;
    }


    @PostMapping("/save")
    public boolean save(@RequestBody Questionnaire q){
        return questionnaireServiceImpl.saveOrUpdate(q);
    }
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id){
        return questionnaireServiceImpl.removeById(id);
    }
    @PostMapping("/del/batch")
    public boolean delete(@RequestBody List<Integer> ids){
        return questionnaireServiceImpl.removeBatchByIds(ids);
    }
}
